package com.cqan.box.controller;

import static com.cqan.common.ViewName.*;

import java.io.File;
import java.util.Calendar;
import java.util.List;
import java.util.StringTokenizer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.cqan.box.entity.Application;
import com.cqan.box.service.ApplicationService;
import com.cqan.controller.BaseController;
import com.cqan.exception.AppException;
import com.cqan.orm.Page;
import com.cqan.orm.PropertyFilter;
import com.cqan.system.entity.SystemConfig;
import com.cqan.system.service.SystemConfigService;
import com.cqan.util.encode.EncodeUtils;
import com.google.common.collect.Lists;

@Controller
@RequestMapping("/application")
public class ApplicationController  extends BaseController<Application>{

	@Resource(name="applicationService")
	private ApplicationService applicationService;
	
	@Resource(name="systemConfigService")
	private SystemConfigService systemConfigService;
	
	@RequestMapping(value="/list.htm")
	public ModelAndView list(Integer pageNo,HttpServletRequest request){
		ModelAndView mav = new ModelAndView(APPLICATION_LIST);
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(request);
		page.setPageNo(pageNo);
		page.setOrder(Page.DESC);
		page.setOrderBy("id");
		page = applicationService.search(page, filters);
		mav.addObject("page", page);
		return mav;
	}
	
	@RequestMapping(value="/edit.htm",method=RequestMethod.GET)
	public ModelAndView edit(Long id,Integer pageNo)throws AppException{
		ModelAndView mav = new ModelAndView(APPLICATION_EDIT);
		if (id!=null) {
			Application application = applicationService.get(id);
			mav.addObject("application", application);
		}
		mav.addObject("pageNo", pageNo);
		return mav;
	}
	
	
	@RequestMapping(value="/modify.htm",method=RequestMethod.POST)
	public ModelAndView modify(Long id,HttpServletRequest request)throws AppException{
		ModelAndView mav = new ModelAndView(new RedirectView("list.htm?pageNo="+request.getParameter("pageNo")));
		try {
			Application a = this.getRequestEntity(request);
			if(id!=null){
				Application application = this.applicationService.get(id);
				this.copyProperties(application,a);
				this.applicationService.update(application);
			}else{
				a.setCtime(Calendar.getInstance().getTime());
				this.applicationService.add(a);
			}
		} catch (Exception e) {
			e.printStackTrace();
			 mav = new ModelAndView(APPLICATION_LIST);
			throw new AppException();
		} 
		return  mav;
	}
	

	@ResponseBody
	@RequestMapping(value="/delete.htm")
	public String delete(String ids)throws AppException{
		try {
			if (ids!=null) {
				StringTokenizer st = new StringTokenizer(ids,"-");
				List<Long> list = Lists.newArrayList();
				while (st.hasMoreTokens()) {
					String id = st.nextToken();
					if (id!=null&&!"".equals(id)) {
						list.add(Long.parseLong(id));
					}
				}
				applicationService.delete(list);
				return "删除成功！";
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "该角色正在使用，暂时不能删除！";
		}
		return "参数异常！";
	}
	
	@ResponseBody
	@RequestMapping(value = "/upload.htm", method = RequestMethod.POST)
	public String upload(HttpServletRequest request) throws AppException {
		try {
			String uploader = request.getParameter("uploader");
			SystemConfig systemConfig = systemConfigService.getKey("cert.file.path");
			String savepath = systemConfig.getValue();
			if (uploader != null) {
				savepath = savepath + uploader;
			}
			StringBuffer sb = new StringBuffer();
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile attachment = multipartRequest.getFile("attachment");
			if (attachment.isEmpty()) {
				throw new AppException("upload.file");
			}
			String fileName = attachment.getOriginalFilename();
			String suffix = null;
			int li = fileName.lastIndexOf(".");
			if (li != -1) {
				suffix = fileName.substring(li, fileName.length());
			}
			if (suffix == null) {
				throw new AppException("upload.suffix");
			}
			String saveFilePath = new StringBuffer().append(savepath)
					.append(createSavePath()).toString();
			File tempsaveFile = new File(saveFilePath);
			if (!tempsaveFile.exists()) {
				tempsaveFile.mkdirs();
			}
			String md5 = EncodeUtils.md5(attachment.getInputStream());
			String url = saveFilePath + md5 + suffix;
			File savefile = new File(url);
			savefile.deleteOnExit();
			FileCopyUtils.copy(attachment.getBytes(), savefile);
			sb.append(url);
			System.out.println(sb.toString());
			return sb.toString();

		} catch (Exception e) {
			e.printStackTrace();
			throw new AppException("upload.unknown");
		}
	}
	
	/**
	 * 按日期生成路径如：/2012/7/23/
	 * 
	 * @return
	 */
	public String createSavePath() {
		Calendar calendar = Calendar.getInstance();
		String path = new StringBuffer("/")
				.append(String.valueOf(calendar.get(Calendar.YEAR)))
				.append("/").append(calendar.get(Calendar.MONTH) + 1)
				.append("/").append(calendar.get(Calendar.DATE)).append("/")
				.toString();
		return path;
	}
}
